package com.shop.controller;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;

import org.omg.CORBA.Request;

import com.jf.core.AuthInterceptor;
import com.jf.core.BaseController;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;
import com.shop.bean.AddressBean;
import com.shop.bean.OrderProductBean;
import com.shop.bean.POrderBean;
import com.shop.bean.ProductBean;
import com.shop.bean.ShopcartBean;
import com.shop.bean.ShrmessBean;
import com.shop.bean.UserBean;
import com.shop.bean.ZhifuBean;
import com.shop.utils.Conf;
import com.shop.utils.MD5Utils;
import com.shop.utils.StringUtils;

/**
 * 购物车 控制器
 * @author bsh_2012@163.com
 *
 */
public class CCartController extends BaseController {
	// 添加商品到购物车
	public void addcart(){
		String pcode = getPara("pcode");
		render(WIEW_WEB+"cart-pro-add.jsp");
	}
	
	/**
	 * 购物车中信息加载
	 * */
	public void cart(){
		UserBean user = getSessionAttr("user");
		if(user == null){
			Cookie[] cookies = getCookieObjects();
			List<ProductBean> list = new ArrayList<ProductBean>();
			if(cookies == null || cookies.length < 0){
				renderJson("product",list);
			}else{
				float sumprice = 0.0f;
				for(Cookie c: cookies){
					if(c.getName().startsWith(Conf.PRODUCT_COOKIE_NAME)){
						String name = c.getName();
						String pcode = name.substring(name.lastIndexOf("_")+1);
						ProductBean product = ProductBean.productDao.findById(pcode);
						sumprice += Float.parseFloat(String.valueOf(product.get("phyprice")))*Integer.parseInt(c.getValue());
						product.set("phyprice", product.get("phyprice")+"*"+c.getValue());
						list.add(product);
					}
				}
				setAttr("sumprice",sumprice);
				setAttr("shopcart",list);
			}
		}else{
			String ucode = user.getStr("ucode");
			String sql_ = StringUtils.getSql("sql.find.findShopCartByUcode", ucode);
			List<Record> list = Db.find(sql_);
			String sql2_ = StringUtils.getSql("sql.sum.userShopCart", ucode);
			Record sumPrice = Db.findFirst(sql2_);
			setAttr("sumprice",sumPrice.get("sumprice"));
			setAttr("shopcart",list);
		}
		render(WIEW_WEB+"cart-pro-one.jsp");
	} 
	
	// 去付款
//	@Before(AuthInterceptor.class)
	public void apply(){
		UserBean user = getSessionAttr("user");
		String ucode = user.getStr("ucode");
		String sumprice = getPara("sumprice");
		String pcodes = getPara("pcodes");
		String[] pcodeArr = pcodes.split("@");
		String sql_ = StringUtils.getSql("sql.find.findAddrByUcode", ucode);
		List<AddressBean> addresses = AddressBean.addressDao.find(sql_);
		String sql_2 = StringUtils.getSql("sql.find.findZhifu");
		List<ZhifuBean> zflist = ZhifuBean.zhifuDao.find(sql_2);
		List<Record> records = new ArrayList<Record>();
		for (String pcode : pcodeArr) {
			String sql2_ = StringUtils.getSql("sql.find.findShopCartByUPcode",
					ucode, pcode);
			Record record = Db.findFirst(sql2_);
			records.add(record);
		}
		setAttr("precords", records);
		setAttr("addresses", addresses);
		setAttr("addsize",addresses.size());
		setAttr("sumprice", sumprice);
		setAttr("zhifus",zflist);
		setAttr("pcodes",pcodes);
		render(WIEW_WEB + "cart-pro-sec.jsp");
	}
	// 现在购买
	public void applynow(){
		UserBean user = getSessionAttr("user");
		String ucode = user.getStr("ucode");
		String pcode = getPara("pcode");
		// 送货地址
		String sql_ = StringUtils.getSql("sql.find.findAddrByUcode", ucode);
		List<AddressBean> addresses = AddressBean.addressDao.find(sql_);
		// 支付方式
		String sql_2 = StringUtils.getSql("sql.find.findZhifu");
		List<ZhifuBean> zflist = ZhifuBean.zhifuDao.find(sql_2);
		// 商品详情
		String sql = "SELECT p.*,dl.dlname,1 pnum ,xl.xlname,dp.dpname from tblproduct p left join tblnzcpdl dl ON  dl.dlcode = p.pdlcode "+
				"left join tblnzcpxl xl ON  xl.xlcode = p.pxlcode "+
				"left join tbldpgl dp ON dp.dpcode = p.pdpcode where p.pcode =?";
		List<ProductBean> records = ProductBean.productDao.find(sql, pcode);
		
		setAttr("sumprice", records.get(0).getStr("phyprice"));
		setAttr("precords", records);   
		setAttr("addresses", addresses);
		setAttr("zhifus",zflist);
		setAttr("pcodes",pcode);
		render(WIEW_WEB + "cart-pro-sec.jsp");
	}
	
	// 提交订单
	public void order(){
		UserBean user = getSessionAttr("user");
		if(user == null){
			//跳转到用户登录页面----------------------------------------------------------------
			//跳转到用户登录页面----------------------------------------------------------------
			//跳转到用户登录页面----------------------------------------------------------------
		}else{
			final String adcode = getPara("address");
			final String pcodes = getPara("pcodes");
			final String sumprice = getPara("sumprice");
			final String zhifu = getPara("zhifu");
			final String ucode = user.getStr("ucode");
			final String shouhuo = getPara("descp");// 配送备注
			
			boolean bool = Db.tx(new IAtom(){
				@Override
				public boolean run() throws SQLException {
					// 订单表
					POrderBean porder = new POrderBean();
					String ocode = StringUtils.getTimeCode();
					boolean bool1 = porder
					                .set("ocode", ocode)
					                .set("ucode", ucode)
					                .set("oprice", Float.parseFloat(sumprice))
					                .set("otime", StringUtils.getFormatTime(new Date()))
					                .set("fukuan", zhifu)
					                .set("ostate", 1)//订单是否生效
					                .set("odeal","1")
					                .set("shouhuo", shouhuo)
					                .save();
					// 订单 商品表
					OrderProductBean opbean = new OrderProductBean();
					boolean flag = true;
					String[] pcodeArr = pcodes.split("@");
					for(String pcode : pcodeArr){
					ProductBean product = ProductBean.productDao.findById(pcode);
					String sql_ = StringUtils.getSql("sql.find.findUserShopcart",ucode,pcode);
					ShopcartBean shopcart = ShopcartBean.scDao.findFirst(sql_);
					boolean bool2 = opbean
						            .set("opcode", StringUtils.getTimeCode())
						            .set("ocode", ocode)
						            .set("pcode", pcode)
						            .set("psum", shopcart.get("pnum"))
						            .set("pzongjia", product.get("phyprice"))
						            .set("pjifen", product.get("khjf"))
						            .save();
					boolean boolFlag = shopcart.delete();
					flag = flag && bool2 && boolFlag;
					}
					ShrmessBean shrmess = new ShrmessBean();
					boolean bool3 = shrmess
							        .set("shrcode", StringUtils.getTimeCode())
							        .set("ocode", ocode)
							        .set("ucode", ucode)
							        .set("adcode", adcode)
							        .set("zffs", zhifu)
							        .save();
					
					if(bool1 && flag && bool3){
						setAttr("sumprice",sumprice);
						setAttr("ocode",porder.get("ocode"));
					}
					return bool1 && flag && bool3;
				}
			});
			
			if(bool){
				render(WIEW_WEB+"cart-pro-thre.jsp");
			}else{
				
			}
		}
		
	}
	
	//修改制定购物车中的商品的数量
	public void modifyShopCartPro(){
		String pcode = getPara("pcode");
		String pnum = getPara("pnum").trim();
		UserBean user = getSessionAttr("user");
		boolean flag = true;
		if(user == null){
			Cookie c =new Cookie(Conf.PRODUCT_COOKIE_NAME+pcode, pnum);
			fixCookie(c, pnum);
		}else{
			String ucode = user.getStr("ucode");
			String sql_ = StringUtils.getSql("sql.find.findUserShopcart", ucode, pcode);
			flag = ShopcartBean.scDao.findFirst(sql_).set("pnum", Integer.parseInt(pnum)).update();
		}
		
		if(flag){
			renderJson("message","true");
		}else{
			renderJson("message","false");
		}
	}
	
	//删除所有选中的购物车中的商品
	public void delShopCartPros(){
		boolean bool = true;
		final String[] pcodeArr = getPara("pcodes").split("@");
		UserBean user = getSessionAttr("user");
		if(user == null){
			for(String pcode : pcodeArr){
				System.out.println(pcode+"--------------");
				Cookie c = getCookieObject(Conf.PRODUCT_COOKIE_NAME+pcode);
				c.setMaxAge(0);
				setCookie(c);
			}
		}else{
			final String ucode = user.getStr("ucode");
			bool = Db.tx(new IAtom() {
				@Override
				public boolean run() throws SQLException {
					boolean result = true;
					for(String pcode : pcodeArr){
						String sql_ = StringUtils.getSql("sql.find.findUserShopcart", ucode, pcode);
						boolean flag = ShopcartBean.scDao.findFirst(sql_).delete();
						result = result && flag;
					}
					return result;
				}
			});
		}
		
		if(bool){
			renderJson("message","true");
		}else{
			renderJson("message","false");
		}
	}
	
	//删除指定购物车中的商品
	public void delShopCartPro(){
		String pcode = getPara("pcode");
		UserBean user = getSessionAttr("user");
		boolean flag = true;
		if(user == null){
			System.out.println("---------------cc");
			Cookie c = getCookieObject(Conf.PRODUCT_COOKIE_NAME+pcode);
			c.setMaxAge(0);
			setCookie(c);
		}else{
			String ucode = user.getStr("ucode");
			String sql_ = StringUtils.getSql("sql.find.findUserShopcart", ucode, pcode);
			flag = ShopcartBean.scDao.findFirst(sql_).delete();
		}
		
		if(flag){
			renderJson("message","true");
		}else{
			renderJson("message","false");
		}
	}
	
	
	///-----------购物车系列的相关操作---------------------------------------------------------//
	/**
	 * 加入购物车
	 * 用户登录前：添加商品ID所标识的cookie到后台，判断本地cookie中是否存在对应的商品，如果已经存在
	 * 则更新cookie，如果还没有存在就添加一个新的cookie
	 * 用户登录后：用户的登录后则信息不用保存到cookie中直接持久化到数据库中
	 * */
		public void addToShoppingCart(){
			boolean result = true;
			String product_id = getPara("pcode");
			String product_num = getPara("pnum");
			UserBean user = getSessionAttr("user");
			Cookie[] cookies = getCookieObjects();
			if(cookies==null || cookies.length<0){
				System.out.println("there is no cookie...");
				if(user == null){
					addCookie(Conf.PRODUCT_COOKIE_NAME+product_id
					          ,String.valueOf(product_num));
				}else{
					String ucode = user.getStr("ucode");
					String sql_ = StringUtils.getSql("sql.find.findUserShopcart",ucode,product_id);
					ShopcartBean scbean = ShopcartBean.scDao.findFirst(sql_);
					if(scbean != null){
						result = scbean.set("pnum", Integer.parseInt(product_num)).update();
					}else{
						ShopcartBean nscbean = new ShopcartBean();
						result = nscbean
								 .set("sccode", StringUtils.getTimeCode())
								 .set("pcode",product_id)
								 .set("ucode", ucode)
								 .set("pnum", Integer.parseInt(product_num))
								 .save();
					}
				}
			}else{
				if(user == null){
					boolean flag = true;
					for(Cookie c: cookies){
						//说明该商品已经在cookie中存在，我们只要更新相关信息就可
						if(c.getName().equals(Conf.PRODUCT_COOKIE_NAME+product_id)){
							Integer oldValue = Integer.valueOf(c.getValue());
							Integer newValue = Integer.valueOf(oldValue+Integer.valueOf(product_num));
							fixCookie(c,newValue.toString().trim());
							flag = false;
							break;
						}
					}
					if(flag){
						addCookie(Conf.PRODUCT_COOKIE_NAME+product_id
								          ,String.valueOf(product_num));
					}
				}else{
					String ucode = user.getStr("ucode");
					String sql_ = StringUtils.getSql("sql.find.findUserShopcart",ucode,product_id);
					ShopcartBean scbean = ShopcartBean.scDao.findFirst(sql_);
					if(scbean != null){
						result = scbean.set("pnum", (Integer.parseInt(product_num)+scbean.getInt("pnum"))).update();
					}else{
						ShopcartBean nscbean = new ShopcartBean();
						result = nscbean
								 .set("sccode", StringUtils.getTimeCode())
								 .set("pcode",product_id)
								 .set("ucode", ucode)
								 .set("pnum", Integer.parseInt(product_num))
								 .save();
					}
				}
			}
			if(result){
				render(WIEW_WEB+"cart-pro-add.jsp");
			}
		}
		
		//更新cookie的辅助方法
		public void fixCookie(Cookie c,String value){
			c.setValue(value.trim());
			c.setMaxAge(24 * 60 * 60 * 7);// 设置为2个钟
//			addCookie(c);
			setCookie(c);
		}

		//添加cookie的辅助方法
		public void addCookie(String cookieName,String value){
		    Cookie cookie = new Cookie(cookieName,value);
		    cookie.setMaxAge(24 * 60 * 60 * 7);// 设置为2个钟
//		    addCookie(cookie);
		    setCookie(cookie);
		}
		
		//读取商品购物车cookie的辅助方法
		public void readShopFromCookie(){
			System.out.println("==================================");
			Cookie[] cookies = getCookieObjects();
			if(cookies == null || cookies.length < 0){
				
			}else{
				for(Cookie c: cookies){
					System.out.println("cookie name:"+c.getName()+";cookie value:"+c.getValue());
				}
			}
		}
		
		//获取购物车信息
		public void getShopCat(){
			UserBean user = getSessionAttr("user");
			if(user == null){
				Cookie[] cookies = getCookieObjects();
				List<ProductBean> list = new ArrayList<ProductBean>();
				if(cookies == null || cookies.length < 0){
					renderJson("product",list);
				}else{
					for(Cookie c: cookies){
						if(c.getName().startsWith(Conf.PRODUCT_COOKIE_NAME)){
							String name = c.getName();
							String pcode = name.substring(name.lastIndexOf("_")+1);
							ProductBean product = ProductBean.productDao.findById(pcode);
							product.set("phyprice", product.get("phyprice")+"*"+c.getValue());
							list.add(product);
						}
					}
					renderJson("product",list);
				}
			}else{
				String ucode = user.getStr("ucode");
				String sql_ = StringUtils.getSql("sql.find.findShopCartByUcode", ucode);
				List<Record> list = Db.find(sql_);
				renderJson("product",list);
			}
		}
		
		//持久化cookie中的商品
		public void peristShoppingCartWhenUserLogin(){
			final UserBean user = getSessionAttr("user");
			if(user != null){
				boolean bool = Db.tx(new IAtom() {
					@Override
					public boolean run() throws SQLException {
						boolean result = true;
						Cookie[] cookies = getCookieObjects();
						if(cookies != null){
							for(Cookie c : cookies){
								if(c.getName().startsWith(Conf.PRODUCT_COOKIE_NAME)){
									String name = c.getName();
									String pnum = c.getValue();
									String pcode = name.substring(name.lastIndexOf("_")+1);
									String ucode = user.getStr("ucode");
									String sql_ = StringUtils.getSql("sql.find.findUserShopcart",ucode,pcode);
									ShopcartBean scbean = ShopcartBean.scDao.findFirst(sql_);
									if(scbean != null){
										boolean flag = scbean.set("pnum", (Integer.parseInt(pnum)+scbean.getInt("pnum"))).update();
									    result = result && flag;
									}else{
										boolean flag = new ShopcartBean()
										               .set("sccode", StringUtils.getTimeCode())
										               .set("ucode", ucode)
										               .set("pcode", pcode)
										               .set("pnum", Integer.parseInt(pnum))
										               .save();
										result = result && flag;
									}
								}
							}
						}
						return result;
					}
				});	
				String url = getSessionAttr("url");
				if(bool){
					removeAllCookies();
					if(url != null && !"".equals(url)){
						forwardAction(url);
					//	redirect(getRequest().getContextPath()+url+"?url="+StringUtils.getTimeCode());
						setSessionAttr("url", null);
						getSession().removeAttribute("url");
					}else{
						forwardAction("/wlc/index");
					//	redirect(getRequest().getContextPath()+"/wlc/index?url="+StringUtils.getTimeCode());
					}
				}else{
					forwardAction("/wlc/index");
					//redirect(getRequest().getContextPath()+"/wlc/index?url="+StringUtils.getTimeCode());
				}
			}
		}
		
		//辅助方法  移除所有的cookie
		public void removeAllCookies(){
			Cookie[] cookies = getCookieObjects();
			if(cookies == null || cookies.length < 0){
				System.out.println("there is no cookie...");
			}else{
				for(Cookie c : cookies){
					if(c.getName().startsWith(Conf.PRODUCT_COOKIE_NAME)){
						c.setMaxAge(0);
//						addCookie(c);
						removeCookie(c.getName());
					}
				}
			}
		}
	
	//登录并持久化cookie信息
	public void loginToSys(){
		String uname = getPara("username");
		
		String pwd = getPara("pwd");
		String sql = StringUtils.getSql("sql.find.findUserInfoByUserName",uname);
		final UserBean user = UserBean.dao.findFirst(sql);  // ujuese = 0 是普通用户
		if(user !=null && "0".equals(user.getStr("ujuese")) && MD5Utils.makeMD5Password(pwd, user.getStr("uencry"))
						.equals(user.getStr("upass"))){
			logger.info("用户登录："+uname);
			setSessionAttr("user", user);
			setSessionAttr("uname", user.getStr("uname"));
			user.set("lasttime", StringUtils.getFormatTime(new Date())).update();
				boolean bool = Db.tx(new IAtom() {
					@Override
					public boolean run() throws SQLException {
						boolean result = true;
						Cookie[] cookies = getCookieObjects();
						if(cookies != null){
							for(Cookie c : cookies){
								if(c.getName().startsWith(Conf.PRODUCT_COOKIE_NAME)){
									String name = c.getName();
									String pnum = c.getValue();
									String pcode = name.substring(name.lastIndexOf("_")+1);
									String ucode = user.getStr("ucode");
									String sql_ = StringUtils.getSql("sql.find.findUserShopcart",ucode,pcode);
									ShopcartBean scbean = ShopcartBean.scDao.findFirst(sql_);
									if(scbean != null){
										boolean flag = scbean.set("pnum", (Integer.parseInt(pnum)+scbean.getInt("pnum"))).update();
									    result = result && flag;
									}else{
										boolean flag = new ShopcartBean()
										               .set("sccode", StringUtils.getTimeCode())
										               .set("ucode", ucode)
										               .set("pcode", pcode)
										               .set("pnum", Integer.parseInt(pnum))
										               .save();
										result = result && flag;
									}
								}
							}
						}
						return result;
					}
				});	
				if(bool){
					removeAllCookies();
					renderJson("message","ok");
				}else{
					renderJson("message","noRegist");
				}
		}else{
			renderJson("message","no");
		}
	}
	
}
